<template>
  <n-space vertical>
    <n-button attr-type="button" type="primary" @click="refreshTables">
      刷新
    </n-button>
    <n-transfer
      ref="transfer"
      v-model:value="checkedTables"
      virtual-scroll
      :options="tables"
      source-filterable
      target-filterable
      source-filter-placeholder="输入表名搜索"
      target-filter-placeholder="输入表名搜索"
      :on-update:value="changeHandle"
    />
  </n-space>
</template>
<script setup lang="ts">
import { ref, Ref, inject, watchEffect } from "vue";
import { useMessage, TransferOption } from "naive-ui";
import { dbTables } from "@/utils/api";
import { DB_CONNECTED_INJECT } from "@/types/constant";
// 信息提示
const message = useMessage();
// 数据表集合
const tables = ref<TransferOption[]>([]);
const checkedTables = ref<string[]>([]);

// 请求API：刷新数据表集合
const refreshTables = async () => {
  const res = await dbTables();
  if (res.code !== 200) {
    message.error(res.message || "获取数据表失败");
    return;
  }
  const data = res.data || [];
  const tabs: TransferOption[] = [];
  data.forEach((element) => {
    tabs.push({
      label: element,
      value: element,
      disabled: false,
    });
  });
  tables.value = tabs;
  checkedTables.value = [];
};
const clearTables = () => {
  tables.value = [];
  checkedTables.value = []
}

// 选择改变监听，推送到父组件
const emit = defineEmits(["selected"]);
const changeHandle = (data: string[]) => {
  checkedTables.value = data;
  emit("selected", data);
};

// 注入数据库连接状态
const isConnected = inject(DB_CONNECTED_INJECT) as Ref<boolean>;
watchEffect(() => {
  if (isConnected.value) {
    refreshTables()
  } else {
    clearTables()
  }
});
</script>
<style scoped></style>
